﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Administration.Health;

namespace SPHealth.SharePoint.HealthRules
{
    public class common
    {
        #region Constants
        public const string LIST_RuleConfigurations = "Health Analyzer Rule Configurations";
        #endregion

        #region Helper Functions        
        /// <summary>
        /// Gets the SPWeb object for the Central Admin site
        /// </summary>
        /// <returns>An SPWeb object that is the current Central Admin site for the farm.</returns>
        public static SPWeb GetCentralAdminWeb()
        {
            // get the central admin SPWeb
            foreach (SPWebApplication webApplication in SPWebService.AdministrationService.WebApplications)
            {
                if (webApplication.IsAdministrationWebApplication)
                {
                    using (SPSite site = new SPSite(webApplication.Sites[0].ID))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            return web;
                        }
                    }
                }
            }
            return null;
        }

        /// <summary>
        /// Returns the settings for the rule
        /// </summary>
        /// <param name="key">The key for the setting value to be returned.</param>
        /// <param name="ruleTitle">The title of the rule from which a setting value should be returned.</param>
        /// <returns>A rule setting value as a string.</returns>
        public static string GetRuleSetting(string key, string ruleTitle)
        {
            if (string.IsNullOrEmpty(key))
                return null;
            if (string.IsNullOrEmpty(ruleTitle))
                return null;

            using (SPWeb centralAdminWeb = GetCentralAdminWeb())
            {
                SPList configList = centralAdminWeb.Lists.TryGetList(LIST_RuleConfigurations);
                if (configList != null)
                {
                    // create a query to get our settings by name
                    SPQuery query = new SPQuery();
                    query.Query = string.Format("<Where><Eq><FieldRef Name=\"Title\"/><Value Type=\"Text\">{0}</Value></Eq></Where>", ruleTitle);
                    
                    // get our list item
                    SPListItemCollection items = configList.GetItems(query);
                    if (items.Count > 0)
                    {
                        // assumes the first item return is the correct one
                        // there should only be one per title as the title column is indexed and has EnforceUniqueValues enabled
                        SPListItem configItem = items[0];

                        // convert our settings to xml
                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(configItem["Settings"].ToString());

                        foreach (XmlNode property in doc.SelectNodes("/Properties/Property"))
                        {
                            if (property.Attributes["Key"].Value == key)
                                return property.Attributes["Value"].Value;
                        }
                    }
                }
            }
            return null;
        }
       
        /// <summary>
        /// Replaces occurances of Environment Variables.
        /// </summary>
        /// <param name="location">The string that may contain environment variables.</param>
        /// <returns>The location parameter with environment variable names replaced with environemnt variable values.</returns>
        public static string ReplaceEnvironmentVariables(string location)
        {
            foreach (string key in Environment.GetEnvironmentVariables().Keys)
            {
                location = location.Replace("%" + key + "%", Environment.GetEnvironmentVariable(key));
                location = location.Replace("%" + key.ToLower() + "%", Environment.GetEnvironmentVariable(key));
                location = location.Replace("%" + key.ToUpper() + "%", Environment.GetEnvironmentVariable(key));
            }
            return location;
        }
        #endregion
    }
}
